package communication;


import javax.annotation.Resource;

/**
 * 线程间的交流1
 * 子线程循环 10 次，接着主线程循环 100 次，接着又回到子线程循环 10 次，
 * 接着再回到主线程又循环 100 次，如此循环50次
 * 
 * 
 * 关于wait notify的一个惨痛教训
 * @author lcx
 *
 */
public class FatherSonExchange extends Thread{

	static boolean isSub=true;
	public static void main(String[] args) 
	{
		FatherSonExchange fse=new FatherSonExchange();
		SubThread sub=new SubThread(fse);
		fse.start();
		sub.start();
	}

	public synchronized void runMain()
	{
		if(isSub)
		{
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=100;i++)
			System.out.println("主线程循环次数   "+i);
		isSub=!isSub;
		notify();
	}

	public synchronized void runSub()
	{
		if(!FatherSonExchange.isSub)
		{
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for(int i=1;i<=10;i++)
			System.out.println("子线程循环次数   "+i);
		FatherSonExchange.isSub=!FatherSonExchange.isSub;
		System.out.println(FatherSonExchange.isSub);
		notify();
	}
	
	@Override
	public void run() {
		for(int i=1;i<=50;i++)
		{
			runMain();
		}
	}
}


class SubThread extends Thread
{
	FatherSonExchange father;
	public SubThread(FatherSonExchange father)
	{
		this.father=father;	
	}

	@Override
	public void run()
	{
		for(int i=1;i<=50;i++)
		{
			father.runSub();
		}

	}


}